package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        Object username1 = request.getAttribute("username");
        if (username1 != null){
            System.out.println("已登录");
        }

        // 接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // null 判断，合法性、有效性判断
        if (username != null && password != null
                && "admin".equalsIgnoreCase(username) // jdbc 连接数据库, 从数据库中查询
             && "a123456".equals(password)){
            // 登录成功
            // 记录登录状态
            request.setAttribute("login", true);
            request.setAttribute("username", username);

            // 转发到 indexServlet
//            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index");
//            requestDispatcher.forward(request, response);
            request.getRequestDispatcher("index").forward(request, response);
            return; // 结束方法
        } else{
            // 登录失败
            response.getWriter().println("login failed. username or password is wrong");
        }

        // 无代码
    }
}
